package com.example.userdemo.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.userdemo.util.ErrorCode;
import com.example.userdemo.util.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RetaLimitInterceptor implements HandlerInterceptor {

    @Resource
    private Jedis jedis;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (jedis.exists("limit")){
            response.setContentType("application/json;charset=UTF-8");
            String resp = JSON.toJSONString(Response.failure(ErrorCode.UNKNOWN_ERROR, "接口限流中"));
            response.getWriter().print(resp);
            return false;
        }else {
            jedis.setex("limit",10, "ok");
            return true;
        }
    }
}
